<template>
  <div>
    <!-- 图片上传 -->
    <el-upload class="avatar-uploader" action="" :show-file-list="false" :http-request="uploadImg">
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
    <!-- 进度条 -->
    <el-progress class="upload-progress" v-if="percentage > 0 && percentage < 100" :percentage="percentage"></el-progress>
  </div>
</template>

<script>
// https://cloud.tencent.com/document/product/436/11459
// npm i cos-js-sdk-v5 --save 安装cos-js-sdk
import COS from 'cos-js-sdk-v5'

let cos = new COS({
  SecretId: 'AKIDZ0QfZESYR5UIuHP0VrzxUu7uY2ILPND4',
  SecretKey: '376uhSEysNiuukT0MURQOHh7QZXN1Uml'
})
export default {
  data() {
    return {
      imageUrl: '',
      percentage: 0
    }
  },
  methods: {
    /** 将图片上传到腾讯云 */
    uploadImg(data) {
      // console.log(data)
      let that = this
      cos.uploadFile(
        {
          Bucket: 'avatar-upload-1259024747' /* 填写自己的bucket，必须字段 */,
          Region: 'ap-nanjing' /* 存储桶所在地域，必须字段 */,
          Key: new Date().toLocaleString().replace(/[ \/\:]/g, '-') /* 存储在桶里的对象键（例如:1.jpg，a/b/test.txt，图片.jpg）支持中文，必须字段 */,
          Body: data.file, // 上传文件对象
          SliceSize: 1024 * 1024 * 3 /* 触发分块上传的阈值，超过3MB使用分块上传，小于5MB使用简单上传。可自行设置，非必须 */,
          onProgress: function (progressData) {
            // console.log(JSON.stringify(progressData))
            that.percentage = progressData.percent * 100
          }
        },
        function (err, data) {
          if (err) {
            console.log('上传失败', err)
          } else {
            console.log('上传成功', data)
            that.imageUrl = 'http://' + data.Location
          }
        }
      )
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #b7b6b6;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
::v-deep .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
::v-deep .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

::v-deep .upload-progress {
  width: 230px;
}
</style>
